import { reactive } from 'vue'
import { simpleToast } from './useUI'
import { createCode } from '../common/verifyCode'
import { request } from '../common/http'
import { useUserStore } from '../store/user'
import { ApiUrl } from '../common/ApiUrl'
import { Toast } from "@/utils";

export default function() {

  const loginForm = reactive({
    mobile: '',
    password: '',
    code: '1',
    checked:  '',
    autologon: '',
    _code: ''
  })

  const initCode = () => {
    loginForm._code = createCode()
  }

  const login = () => {
    if (!loginForm.mobile) {
      Toast("请输入账号!");
      return;
    }
    if (!loginForm.password) {
      Toast("请输入密码!");
      return;
    }
    if (!loginForm.code) {
      Toast("请输入验证码!");
      return;
    }
    const data = {
      mobile: loginForm.mobile,
      password: loginForm.password,
    }
    request({ url: ApiUrl.LoginUrl, method: 'PUT', data }).then(res => {
			console.log(res)
			if (res.status == 0) {
				useUserStore().setUserInfo(res.data)
				uni.switchTab({url: '/pages/index/index'});
			} else {
				Toast("登录失败，账号或密码有误！", "error")
			}
			
    })
  }

  const logout = () => {
		uni.removeStorageSync('cookie')
    uni.redirectTo({url: '/pages/login/index'})
  }

  return {
    loginForm, login, initCode, logout
  }
}